#include "ccarlogin.h"
#include <QDataStream>
#include <QTcpSocket>
#include "protocol/srvloginansToCar.h"

CCarLogin::CCarLogin(QObject *parent)
    :INetWorking(parent)
{
}

CCarLogin::~CCarLogin()
{
}

void CCarLogin::prepareWriteData(QByteArray* block, void* param)
{
    // we cannot discrete this definition to the outside of the block,
    // and pass the reference to the funtion, or it will cause some
    // unknown problems, such as wrong streams. Maybe it is a bug of QT.
    QDataStream out(block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);


    protocal::CarLogin* pCarLogin = (protocal::CarLogin*)param;

    // output the head information
    out << (qint32)(pCarLogin->source) \
        << (qint32)(pCarLogin->cli_command) \
        << (qint32)(pCarLogin->size);

    // output the body information

    //
    char * temp = new char [10];
    // we must do so, because the constructor of QString(char*) will truncate the
    // remaining space after '\0', and we need them to occupy the space.
    memcpy(temp, pCarLogin->user_name, 10);
    out << temp;

    memcpy(temp, pCarLogin->password, 10);
    out << temp;

    delete [] temp;
}

bool CCarLogin::prepareReadData(QTcpSocket *pTcpSocket, protocal::BasePtc *basePtc)
{
    QDataStream in(pTcpSocket);

    if (   basePtc->source != protocal::SERVER\
        || basePtc->srv_command != protocal::SRV_LOGINANS\
        || basePtc->size != sizeof(protocal::SrvLoginAns)+4)
    {
        // TODO: check whether it is necessary to clear the contents of in or pTcpSocket.
        // make an experiment to verify it.
        return false;
    }

    // recieve data, from srvloginans.h
    in >> ans; //directly read integer into ans
    char *temp = new char[10];
    in >> temp;
    memcpy(driver_id, temp, 10);
    delete [] temp;
    this->formResult();

    return true;
}

void CCarLogin::formResult()
{
    resultMap.insert(QString("answer"), QString::number((int)ans));
    resultMap.insert(QString("driver_id"), QString(driver_id));
}
